package com.answer.wx.gateway.config.exception;

import com.alibaba.fastjson.JSON;
import com.answer.wx.common.exception.RequestException;
import com.answer.wx.common.response.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * GlobalExceptionHandler
 * @description 全局异常
 * @author answer_wx
 * @date 2022/8/3 22:58
 * @version 1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler(value = RequestException.class)
    @ResponseBody
    public void customerException(HttpServletRequest req, HttpServletResponse res, RequestException ex) throws Exception {
        log.debug("自定义异常:" + ex);
        ex.printStackTrace();

        ApiResponse response = ApiResponse.error(ex.getCode(),ex.getMessage());
        respData(res, response);
    }


    /**
     * 输出数据
     * @param res
     * @param data
     * @throws Exception
     */
    private void respData(HttpServletResponse res, Object data) throws Exception {
        res.setContentType("application/json;charset=utf-8");
        res.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter printWriter = res.getWriter();
        printWriter.write(JSON.toJSONString(data));
        printWriter.flush();
        printWriter.close();
    }
}
